package com.learn.temp.api;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 统计文件夹下文件的大小
 *
 * @author wangxing
 * @version 2020/5/26 21:51 Administrator
 */
public class FilesUser {
    private final static ForkJoinPool forkJoinPool = new ForkJoinPool();

    private static class FileSizeFinder extends RecursiveTask<Long> {
        final File file;

        public FileSizeFinder(final File theFile) {
            file = theFile;
        }

        @Override
        public Long compute() {
            long size = 0;
            if (file.isFile()) {
                size = file.length();
            } else {
                final File[] children = file.listFiles();
                if (children != null) {
                    List<ForkJoinTask<Long>> tasks = new ArrayList<ForkJoinTask<Long>>();
                    for (final File child : children) {
                        if (child.isFile()) {
                            size += child.length();
                        } else {
                            tasks.add(new FileSizeFinder(child));
                        }
                    }
                    for (final ForkJoinTask<Long> task : invokeAll(tasks)) {
                        size += task.join();
                    }
                }
            }
            if (!file.isFile()) {
                int temp = (int) size >>> 20;
                if ((temp) > 100) {
                    System.out.println("file name is " + file.getPath() + " size is " + (temp) + "M");
                }

            }
            return size;
        }
    }

    public static void getFileSize(String path) {
        System.out.println(path);
        long start = System.currentTimeMillis();
        final long total = forkJoinPool.invoke(new FileSizeFinder(new File(path)));
        System.out.println((total >>> 30) + "G");
        long end = System.currentTimeMillis();
        System.out.println((end - start) / 1000 + "s");

    }
}
